# -*- coding:utf-8 -*-

__author__='zhaoxp'

from urlparse import parse_qs

'''
使用辅助函数来取代复杂的表达式

这里给出一个复杂表达式的例子if/else，例如： red = int(red[0]) if red[0] else 0
'''

def get_first_int(values, key, default=0):
    found = values.get(key,[''])
    if found[0]:
        found = int(found[0])
    else:
        found = default
    return found


if __name__=='__main__':
    #a='abcdefgh'
    my_values = parse_qs('red=5&blue=0&green=', keep_blank_values=True)
    print type(my_values),'->',my_values
    print(repr(my_values))
    print

    print('Red:   ',my_values.get('red'))
    print('Green: ',my_values.get('green'))
    print('Opacity:',my_values.get('opacity'))
    print

    red     = my_values.get('red',    [''])[0] or 0
    green   = my_values.get('green',  [''])[0] or 0
    opacity = my_values.get('opacity',[''])[0] or 0
    print('Red:     %r'%red)
    print('Green:   %r'%green)
    print('Opacity: %r'%opacity)
    print

    red = int(my_values.get('red',[''])[0] or 0)
    print type(red),'->',red
    print

    red = my_values.get('red',[''])
    red = int(red[0]) if red[0] else 0
    print type(red),'->',red
    print

    green = my_values.get('green',[''])
    if green[0]:
        green = int(green[0])
    else:
        green = 0
    print type(green),'->',green
    print

    green = get_first_int(my_values,'green')
    print type(green),'->',green